import 'package:flutter/material.dart';
import 'package:flutter_bmfutils/BaiduMap/bmfmap_utils.dart';
import 'package:flutter_bmfbase/BaiduMap/bmfmap_base.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:rxdart/rxdart.dart';
import 'package:loxen/api/http_server/adderss.dart';
import 'package:loxen/mode/address_mode.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/widget/empty_widget.dart';
import 'package:loxen/widget/fail_widget.dart';
import 'package:loxen/widget/loading_widget.dart';
import 'package:loxen/widget/my_subassembly.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/view/address/address_item_card.dart' as AddressCard;
import 'package:loxen/view/address/new_address_widget.dart' as NewAddress;

class _ViewModel extends BaseViewModel with AddressMixin {
  final bool showDistance;
  final String id;

  List<Address> list;
  List<List<BMFCoordinate>> locationList = [];
  List<String> locationId = [];
  int index = 0;

  _ViewModel(this.showDistance, this.id);

  loadData() {
    if (mState == BaseState.LOADING) return;
    if (id == null) {
      getAddressList().doOnListen(() {
        mState = BaseState.LOADING;
        notifyListeners();
      }).listen((value) {
        if (value != null && value.length > 0) {
          list = value;
          mState = BaseState.CONTENT;
        } else {
          mState = BaseState.EMPTY;
        }
      }, onError: (error, stack) {
        print(stack);
        print(error);
        mState = BaseState.FAIL;
      }, onDone: () => notifyListeners());
    } else {
      Rx.zip2<List<Address>, dynamic, bool>(getAddressList(), getOperationLists(id),
          (value, event) {
        if (event is List) {
          for (var data in event) {
            if (data is Map) {
              var locations = data['support_city_map'];
              if (locations is List) {
                if (locations.length > 0) {
                  List<BMFCoordinate> listLocation = [];
                  for (var location in locations) {
                    if (location is Map) {
                      listLocation.add(BMFCoordinate(
                          double.parse(location['lat']), double.parse(location['lng'])));
                    }
                  }
                  locationList.add(listLocation);
                  locationId.add(data['id'].toString());
                }
              }
            }
          }
        }
        if (value != null && value.length > 0) {
          list = value;
          if (showDistance) {
            _initBeyond();
          } else {
            mState = BaseState.CONTENT;
            notifyListeners();
          }
        } else {
          mState = BaseState.EMPTY;
          notifyListeners();
        }
        return true;
      }).doOnListen(() {
        mState = BaseState.LOADING;
        notifyListeners();
      }).listen((event) {
        print(event);
      }, onError: (error, stack) {
        mState = BaseState.FAIL;
        notifyListeners();
        print(error);
        print(stack);
      });
    }
  }

  //初始化坐标范围
  void _initBeyond() async {
    for (var data in this.list) {
      data.isBeyond = true;
      for (int i = 0; i < locationList.length; i++) {
        var location = locationList[i];
        bool beyond = await BMFCalculateUtils.polygonContainsCoordinate(
            BMFCoordinate(data.lat, data.lng), location);
        if (beyond) {
          data.centerId = locationId[i];
          data.isBeyond = !beyond;
          break;
        }
      }
    }
    mState = BaseState.CONTENT;
    notifyListeners();
  }
}

class AddressAdministrationWidget extends StatefulWidget {
  final bool showDistance;
  final String id;
  final bool onClick;

  const AddressAdministrationWidget({
    Key key,
    this.showDistance = false,
    this.id,
    this.onClick = true,
  }) : super(key: key);

  @override
  _AddressAdministrationWidgetState createState() => _AddressAdministrationWidgetState();
}

class _AddressAdministrationWidgetState extends State<AddressAdministrationWidget> {
  AddressCard.ItemBean changeAdderss(Address address) {
    return AddressCard.ItemBean(
      address.default_addr,
      address.isBeyond,
      address.area.province,
      address.area.city,
      address.area.district,
      address.address,
      address.signer_name,
      address.signer_mobile,
    );
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<_ViewModel>(
      create: (context) {
        _ViewModel model = _ViewModel(widget.showDistance, widget.id);
        model.loadData();
        return model;
      },
      child: Scaffold(
        appBar: PreferredSize(
          preferredSize: Size(double.infinity, 96.h),
          child: Container(
            color: Theme.of(context).backgroundColor,
            child: SafeArea(
              child: Column(
                children: [
                  Row(
                    children: <Widget>[
                      MySubassembly.getBackIcon(context,
                          color: Theme.of(context).textTheme.subtitle2.color),
                      Expanded(
                        child: Center(
                          child: Text(
                            StringResources.shou_huo_di_zhi,
                            style: TextStyle(
                                fontSize: 32.sp,
                                fontWeight: FontWeight.w500,
                                color: Theme.of(context).textTheme.subtitle2.color),
                          ),
                        ),
                      ),
                      MySubassembly.getSearchIcon(null, text: Text('')),
                    ],
                  ),
                  Divider(height: 1.h)
                ],
              ),
            ),
          ),
        ),
        backgroundColor: Theme.of(context).backgroundColor,
        body: Selector<_ViewModel, BaseState>(
            builder: (context, state, __) {
              Widget content;
              if (state == BaseState.LOADING) {
                return LoadingWidget();
              } else if (state == BaseState.FAIL) {
                return FailWidget(
                  onClick: () {
                    Provider.of<_ViewModel>(context, listen: false).loadData();
                  },
                );
              } else if (state == BaseState.CONTENT) {
                List<Address> data = Provider.of<_ViewModel>(context, listen: false).list;
                content = ListView.builder(
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    itemCount: data.length,
                    itemBuilder: (context, index) {
                      var value = data[index];
                      return Padding(
                        padding: EdgeInsets.only(top: 16.h),
                        child: AddressCard.AdderssItemCard(
                          showDistance: widget.showDistance,
                          onClick: widget.onClick
                              ? () {
                                  if (widget.showDistance) {
                                    if (value.isBeyond) {
                                      Toast.show('超出配送范围', context);
                                    } else {
                                      Navigator.of(context).pop(value);
                                    }
                                  } else {
                                    Navigator.of(context).pop(value);
                                  }
                                }
                              : null,
                          onEdit: () {
                            Navigator.of(context)
                                .push(MaterialPageRoute(
                                    builder: (_) => NewAddress.NewAddressWidget(
                                          locationList: context.read<_ViewModel>().locationList,
                                          bean: NewAddress.ItemBean(
                                            id: value.id.toString(),
                                            defaultAddress: value.default_addr,
                                            province: value.area.province,
                                            city: value.area.city,
                                            district: value.area.district,
                                            detailedAddress: value.address,
                                            userName: value.signer_name,
                                            telephone: value.signer_mobile,
                                            latitude: value.lat,
                                            longitude: value.lng,
                                          ),
                                          showDistance: widget.showDistance ?? false,
                                        )))
                                .then((value) {
                              if (value) {
                                context.read<_ViewModel>().loadData();
                              }
                            });
                          },
                          bean: changeAdderss(value),
                        ),
                      );
                    });
              } else {
                content = Container(
                  height: 800.h,
                  child: EmptyWidget(
                    content: '点击下方加新的地址吧',
                  ),
                );
              }
              return SingleChildScrollView(
                child: Padding(
                  padding: EdgeInsets.only(left: 20.w, right: 20.w),
                  child: Column(
                    children: [
                      content,
                      Padding(
                        padding: EdgeInsets.only(top: 120.h, bottom: 120.h),
                        child: Container(
                          width: double.infinity,
                          height: 90.h,
                          margin: EdgeInsets.only(bottom: 120.h),
                          child: FlatButton(
                              onPressed: () {
                                Navigator.of(context)
                                    .push(MaterialPageRoute(
                                        builder: (_) => NewAddress.NewAddressWidget(
                                              locationList: context.read<_ViewModel>().locationList,
                                              bean: null,
                                              showDistance: widget.showDistance ?? false,
                                            )))
                                    .then((value) {
                                  if (value) {
                                    context.read<_ViewModel>().loadData();
                                  }
                                });
                              },
                              color: Color(0xFF0CACCC),
                              child: Text(
                                '新建收货地址',
                                style: TextStyle(
                                  fontSize: 32.sp,
                                  color: Colors.white,
                                ),
                              )),
                        ),
                      )
                    ],
                  ),
                ),
              );
            },
            selector: (_, model) => model.mState),
      ),
    );
  }
}
